package org.example.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class WebUtils {
	/**
	 * 将字符串渲染到客户端
	 *
	 * @param response
	 * @param string
	 * @return
	 */
	public static String renderString(HttpServletResponse response, String string) {
		try {
			response.setStatus(200);
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public static String printContent(HttpServletResponse response,String content){
		try {
			response.setStatus(401);
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(content);
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	//获取HttpServletRequest实例
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
	}
}

